let defaultLog = true

const color = {
  d: 'color: gray',
  w: 'color: blue',
  e: 'color: red',
}

let arr2strarr = function (arr) {
  return arr.map(function (v) {
    let str = null;

    if (v instanceof Object) {
      try {
        str = JSON.stringify(v)
      } catch (e) {
        str = 'Object'
      }
    } else {
      str = v
    }

    return str
  })
}

let clog = function (level, prefix, ...args) {
  if (defaultLog) {
    console.log('%c' + prefix, color[level], ...args)
  } else {
    console.log('%c' + arr2strarr([prefix].concat(...args)).join(' '),
        color[level])
  }
}

let now = () => {
  let date = new Date()
  return '[' + date.getFullYear() + '-' + (date.getMonth() + 1) + '-'
      + date.getDate()
      + ' ' + date.getHours() + ':' + date.getMinutes() + ':'
      + date.getSeconds() + '.' + date.getMilliseconds() + '] '
}

const kLevelVerbose = 1
const kLevelDebug = 2
const kLevelWarn = 3

class Log {
  constructor(prefix = '', level = kLevelDebug) {
    this.name = prefix
    this.level = level
  }

  static get levelVerbose() {
    return kLevelVerbose
  }

  static get levelDebug() {
    return kLevelDebug
  }

  static get levelWarn() {
    return kLevelVerbose
  }

  static init(app) {
    defaultLog = (app.data.platform === 'web')
  }

  v(...args) {
    if (this.level <= kLevelVerbose) {
      const prefix = now() + this.name

      if (defaultLog) {
        console.log(prefix, ...args)
      } else {
        console.log(arr2strarr([prefix].concat(args)).join(' '))
      }
    }
  }

  d(...args) {
    if (this.level <= kLevelDebug) {
      const prefix = now() + this.name

      if (defaultLog) {
        console.info(prefix, ...args)
      } else {
        console.info(arr2strarr([prefix].concat(...args)).join(' '))
      }
    }
  }

  w(...args) {
    if (this.level <= kLevelWarn) {
      const prefix = now() + this.name

      if (defaultLog) {
        console.warn(prefix, ...args)
      } else {
        console.warn(arr2strarr([prefix, ...args]).join(' '))
      }
    }
  }

  e(...args) {
    const prefix = now() + this.name

    if (defaultLog) {
      console.error(prefix, ...args)
    } else {
      console.error(arr2strarr([prefix, args]).join(' '))
    }
  }

  dd(...args) {
    if (this.level <= kLevelDebug) {
      clog('d', now() + this.name, args)
    }
  }

  ww(...args) {
    if (this.level <= kLevelWarn) {
      clog('w', now() + this.name, args)
    }
  }

  ee(...args) {
    clog('e', now() + this.name, args)
  }
}

export default Log;